package com.emokili.ewa.portal.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import com.emokili.ewa.common.utils.R;
import com.emokili.ewa.core.frame.service.OssService;
import com.emokili.ewa.core.frame.vo.OssVo;
import com.emokili.ewa.core.frame.vo.PhotoUploadVo;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@RequestMapping("/web/photo")
public class PhotoController {


    @Value("${ACCESS_KEY_ID}")
    private String accessKeyId;
    @Value("${ACCESS_KEY_SECRET}")
    private String accessKeySecret;
    @Value("${ROLE_ARN}")
    private String roleArn;
    @Value("${TOKEN_EXPIRE_TIME}")
    private Long tokenExpireTime;
    /**
     * 目前只有"cn-hangzhou"这个region可用, 不要使用填写其他region的值
     **/
    public static final String REGION_CN_HANGZHOU = "cn-hangzhou";
    public static final String STS_API_VERSION = "2015-04-01";


    @Autowired
    private OssService ossService;

    @GetMapping("/upload")
    @ResponseBody
    public OssVo upload(@RequestParam String serialNumber,@RequestParam String playlistId){
        OssVo ossVo = ossService.getOssParams(serialNumber, playlistId);
        return ossVo;
    }

    public static void main(String[] args) {
        //构建一个阿里云客户端，用于发起请求。
        //构建阿里云客户端时需要设置AccessKey ID和AccessKey Secret。
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI5tCdqxJBvF9c93psktaA", "LuDetZgKLU0M5OfQja8FiOsjPknaHF");
        IAcsClient client = new DefaultAcsClient(profile);

        //构造请求，设置参数。关于参数含义和设置方法，请参见API参考。
        AssumeRoleRequest request = new AssumeRoleRequest();
        request.setRegionId("cn-hangzhou");
        request.setLocationProduct("1/2");
        request.setRoleArn("acs:ram::1006960137574003:role/aliyunosstokengeneratorrole");
        request.setRoleSessionName("external-username");
        String bucketName = "ew10a-dev-upload";
        String ossPath = "1";
        String policy = "{\n" +
                "    \"Statement\": [\n" +
                "      {\n" +
                "        \"Action\": [\n" +
                "          \"oss:GetObject\",\n" +
                "          \"oss:PutObject\",\n" +
                "          \"oss:ListObjects\"\n" +
                "        ],\n" +
                "        \"Effect\": \"Allow\",\n" +
                "        \"Resource\": [\"acs:oss:*:*:" + bucketName + "/" + ossPath + "/*\", \"acs:oss:*:*:"+bucketName+"\"]\n" +
                "      }\n" +
                "    ],\n" +
                "    \"Version\": \"1\"\n" +
                "}";
        request.setPolicy(policy);
        //发起请求，并得到响应。
        try {
            AssumeRoleResponse response = client.getAcsResponse(request);
            System.out.println(new Gson().toJson(response));
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }
    }


    public R upload(@RequestBody PhotoUploadVo photoUploadVo) throws ClientException {
        String roleSessionName = "ew10a";
        // 此处必须为 HTTPS
        ProtocolType protocolType = ProtocolType.HTTPS;

        String policy = readJson("E:\\product\\ew10a\\ewa-app\\policy\\bucket_write_policy.txt");
        final AssumeRoleResponse stsResponse = assumeRole(accessKeyId, accessKeySecret, roleArn, roleSessionName,
                policy, protocolType, tokenExpireTime);
        Map<String, String> respMap = new LinkedHashMap<String, String>();
        respMap.put("StatusCode", "200");
        respMap.put("AccessKeyId", stsResponse.getCredentials().getAccessKeyId());
        respMap.put("AccessKeySecret", stsResponse.getCredentials().getAccessKeySecret());
        respMap.put("SecurityToken", stsResponse.getCredentials().getSecurityToken());
        respMap.put("Expiration", stsResponse.getCredentials().getExpiration());
        return R.ok().setData(respMap);

    }

    protected AssumeRoleResponse assumeRole(String accessKeyId, String accessKeySecret, String roleArn,
                                            String roleSessionName, String policy, ProtocolType protocolType, long durationSeconds) throws ClientException {

        // 创建一个 Aliyun Acs Client, 用于发起 OpenAPI 请求
        IClientProfile profile = DefaultProfile.getProfile(REGION_CN_HANGZHOU, accessKeyId, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        // 创建一个 AssumeRoleRequest 并设置请求参数
        final AssumeRoleRequest request = new AssumeRoleRequest();
        request.setVersion(STS_API_VERSION);
        request.setMethod(MethodType.POST);
        request.setProtocol(protocolType);

        request.setRoleArn(roleArn);
        request.setRoleSessionName(roleSessionName);
       // request.setPolicy(policy);
       // request.setDurationSeconds(durationSeconds);

        // 发起请求，并得到response
        final AssumeRoleResponse response = client.getAcsResponse(request);

        return response;
    }

    /**
     * 读取配置文件
     * @param path
     * @return
     */
    private String readJson(String path){
        //从给定位置获取文件
        File file = new File(path);
        BufferedReader reader = null;
        //返回值,使用StringBuffer
        StringBuffer data = new StringBuffer();
        //
        try {
            reader = new BufferedReader(new FileReader(file));
            //每次读取文件的缓存
            String temp = null;
            while((temp = reader.readLine()) != null){
                data.append(temp);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭文件流
            if (reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return data.toString();
    }

    // private void extracted() {
    //     //https://gulimall-clouds.oss-cn-beijing.aliyuncs.com/iqiyi.png
    //
    //     // Endpoint以杭州为例，其它Region请按实际情况填写。
    //     String endpoint = "s3.us-east-2.amazonaws.com";
    //     // 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建。
    //     String accessKeyId = "AKIAXG5FJ3GGXFMAUPAL";
    //     String accessKeySecret = "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";
    //
    //     String bucket = "ew10a-prod-upload"; // 请填写您的 bucketname 。
    //     String host = "https://" + bucket + "." + endpoint; // host的格式为 bucketname.endpoint
    //     // callbackUrl为 上传回调服务器的URL，请将下面的IP和Port配置为您自己的真实信息。
    //     //String callbackUrl = "http://88.88.88.88:8888";
    //
    //     String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
    //     String dir = format + "/"; // 用户上传文件时指定的前缀。
    //     AWSCredentials awsCredentials = new BasicAWSCredentials("AKIAXG5FJ3GGXFMAUPAL", "UTQGlhB9GJT6ViCTZRhZTT4Sj2kc8iZzfqG8YJlJ");
    //     AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
    //             .withRegion(Regions.US_EAST_2)
    //             .withCredentials(new AWSStaticCredentialsProvider(awsCredentials))
    //             .build();
    // }
}
